package com.sdkx.app.ViewModel;

import android.app.UiAutomation;
import android.util.Log;

import com.sdkx.app.gps.GpsManager;
import com.sdkx.app.model.AlarmPoint;
import com.sdkx.app.util.Util;

import org.litepal.LitePal;

import java.util.List;
import java.util.logging.Logger;

import cn.creable.gridgis.geometry.Arithmetic;
import cn.creable.gridgis.geometry.Point;

public class AlarmPointManager {
    private static AlarmPointManager instance = new AlarmPointManager();
    private static String TAG = AlarmPointManager.class.getSimpleName();
    AlarmWorker alarmWorker = new AlarmWorker();

    private AlarmPointManager() {
    }

    public static AlarmPointManager getInstance() {
        return instance;
    }

    public List<AlarmPoint> getAll() {
        return LitePal.findAll(AlarmPoint.class);
    }

    public List<AlarmPoint> getPointsLimite(int limit, int offset) {
        return LitePal.limit(limit).offset(offset).find(AlarmPoint.class);
    }

    public void delete(AlarmPoint point) {
        if (point != null) {
          point.delete();
        }
    }

    public void insert(AlarmPoint point) {
        if (point != null) {
            point.save();
            alarmWorker.notifyAll();
        }
    }

    public void deleteAll() {
        LitePal.deleteAll(AlarmPoint.class);
    }

    public void listen() {
        if (!alarmWorker.isAlive()) {
            alarmWorker.start();
        }
    }

    public class AlarmWorker extends Thread {
        AlarmPoint mCurPoint;

        @Override
        public void run() {
            while (true) {
                List<AlarmPoint> list = getAll();
                if (list.size() == 0 ) {
                    synchronized (this) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(GpsManager.getInstance().getLocation() != null) {
                    for (AlarmPoint point : list) {
                        double distance = Arithmetic.getDistance(GpsManager.getInstance().getLocation().getLongitude(), GpsManager.getInstance().getLocation().getLatitude(), point.getDoubleLongitude(), point.getDoubleLatitude());
                        if (distance < point.getRadius()) {
                            // todo alarm things
                            break;
                        }
                    }
                }
                Log.d(TAG, " alarmming *****************");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
